package art.client.widgets;

import java.util.List;

import art.shared.entities.GenreShared;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class ArtTableFilter implements IsWidget {

	private HorizontalPanel mainPanel = new HorizontalPanel();
	private ListBox searchInDropDown = null;
	private ArtTable artTable = null;
	private Widget searchField = null;
	private Button filterButton = null;

	public ArtTableFilter(ArtTable table, final List<GenreShared> genres) {
		final HorizontalPanel panel = new HorizontalPanel();
		mainPanel.getElement().setId("arttable-filter-mainpanel");
		panel.getElement().setId("arttable-filter-panel");
		this.artTable = table;
		searchInDropDown = new ListBox();
		searchInDropDown.addItem("Title");
		searchInDropDown.addItem("Creator");
		searchInDropDown.addItem("Genre");
		searchInDropDown.getElement().setId("arttable-filter-searchindropdown");
		searchInDropDown.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent arg0) {
				panel.remove(searchField);
				if (searchInDropDown.getItemText(
						searchInDropDown.getSelectedIndex()).equals("Genre")) {
					searchField = new ListBox();
					searchField.getElement().setId("arttable-filter-searchField-dropdown");
					for (GenreShared genre : genres) {
						((ListBox) searchField).addItem(genre.getName());
					}
				} else {
					searchField = new TextBox();
					searchField.getElement().setId("arttable-filter-searchField-textbox");
				}
				panel.add(searchField);
			}
		});
		panel.add(searchInDropDown);
		searchField = new TextBox();
		panel.add(searchField);
		mainPanel.add(panel);
		filterButton = new Button("Search");
		filterButton.getElement().setId("arttable-filter-searchbutton");
		filterButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				String selected = searchInDropDown.getItemText(searchInDropDown
						.getSelectedIndex());
				if (selected.equals("Title")) {
					artTable.applyTitleFilter(((TextBox) searchField).getText());
				} else if (selected.equals("Creator")) {
					artTable.applyCreatorFilter(((TextBox) searchField)
							.getText());
				} else if (selected.equals("Genre")) {
					String genre = ((ListBox) searchField)
							.getItemText(((ListBox) searchField)
									.getSelectedIndex());
					artTable.applyGenreFilter(genre);
				}
			}
		});
		mainPanel.add(filterButton);
	}

	@Override
	public Widget asWidget() {
		return mainPanel;
	}

}
